<template>
  <div class="register-container">
    <el-form ref="registerForm" :model="registerForm" class="register-form" autocomplete="on" label-position="left">
      <div class="title-container">
        <h3 class="title">用户注册</h3>
        <p class="subtitle">欢迎加入清泉到家</p>
      </div>

      <el-form-item>
        <el-input
          ref="username"
          v-model="registerForm.username"
          placeholder="用户名"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
          prefix-icon="el-icon-user"
        />
      </el-form-item>

      <el-form-item>
        <el-input
          ref="password"
          v-model="registerForm.password"
          :type="passwordType"
          placeholder="密码"
          name="password"
          tabindex="2"
          autocomplete="on"
          prefix-icon="el-icon-lock"
        >
          <i slot="suffix" class="el-input__icon el-icon-view" @click="showPassword"></i>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-input
          ref="confirmPassword"
          v-model="registerForm.confirmPassword"
          :type="passwordType"
          placeholder="确认密码"
          name="confirmPassword"
          tabindex="3"
          autocomplete="on"
          prefix-icon="el-icon-lock"
        />
      </el-form-item>

      <el-form-item>
        <el-input
          ref="phone"
          v-model="registerForm.phone"
          placeholder="手机号"
          name="phone"
          type="text"
          tabindex="4"
          autocomplete="on"
          prefix-icon="el-icon-mobile-phone"
        />
      </el-form-item>

      <el-form-item>
        <el-input
          ref="email"
          v-model="registerForm.email"
          placeholder="请输入QQ邮箱 (例如: example@qq.com)"
          name="email"
          type="email"
          tabindex="5"
          autocomplete="on"
          prefix-icon="el-icon-message"
        />
      </el-form-item>

      <el-form-item>
        <div class="verification-code">
          <el-input
            ref="code"
            v-model="registerForm.code"
            placeholder="验证码"
            name="code"
            type="text"
            tabindex="6"
            autocomplete="on"
            prefix-icon="el-icon-key"
            class="code-input"
          />
          <el-button 
            type="primary" 
            class="code-button" 
            :disabled="codeSending || cooldown > 0"
            @click="sendCode"
          >
            {{ cooldown > 0 ? `${cooldown}秒后重试` : '获取验证码' }}
          </el-button>
        </div>
      </el-form-item>

      <el-form-item>
        <el-input
          ref="address"
          v-model="registerForm.address"
          placeholder="地址"
          name="address"
          type="text"
          tabindex="7"
          autocomplete="on"
          prefix-icon="el-icon-location"
        />
      </el-form-item>

      <el-button :loading="loading" type="primary" class="register-button" @click.native.prevent="handleRegister">注册</el-button>

      <div class="login-link">
        <router-link to="/login">
          <span>已有账号？立即登录</span>
        </router-link>
      </div>
    </el-form>
  </div>
</template>

<script>
import { register, sendVerificationCode } from '@/api/auth'

export default {
  name: 'Register',
  data() {
    return {
      registerForm: {
        username: '',
        password: '',
        confirmPassword: '',
        phone: '',
        email: '',
        address: '',
        code: ''
      },
      passwordType: 'password',
      loading: false,
      codeSending: false,
      cooldown: 0,
      timer: null
    }
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    showPassword() {
      this.passwordType = this.passwordType === 'password' ? '' : 'password'
    },
    handleRegister() {
      // 检查必填字段
      if (!this.registerForm.username || !this.registerForm.password || 
          !this.registerForm.email || !this.registerForm.code) {
        this.$message.error('请填写必要的注册信息');
        return;
      }
      
      // 检查密码是否一致
      if (this.registerForm.password !== this.registerForm.confirmPassword) {
        this.$message.error('两次输入的密码不一致');
        return;
      }
      
      // 检查邮箱格式
      if (!this.validateEmail(this.registerForm.email)) {
        this.$message.error('请输入正确的QQ邮箱格式');
        return;
      }
      
      // 直接发送请求
      this.loading = true
      const { username, password, phone, email, address, code } = this.registerForm
      register({
        username,
        password,
        phone,
        email,
        address,
        code,
        role: 'USER' // 默认注册为客户角色
      }).then(response => {
        // 注册成功
        this.$message({
          message: '注册成功，请登录',
          type: 'success',
          duration: 3000
        })
        this.$router.push('/login')
        this.loading = false
      }).catch(error => {
        // 注册失败，错误消息已由全局拦截器处理
        console.error('注册失败:', error)
        this.loading = false
      })
    },
    validateEmail(email) {
      // 验证QQ邮箱格式
      const regex = /^[a-zA-Z0-9_-]+@qq\.com$/;
      return regex.test(email);
    },
    startCooldown() {
      this.cooldown = 60; // 60秒倒计时
      this.timer = setInterval(() => {
        if (this.cooldown > 0) {
          this.cooldown--;
        } else {
          clearInterval(this.timer);
          this.timer = null;
        }
      }, 1000);
    },
    sendCode() {
      // 检查邮箱是否填写
      if (!this.registerForm.email) {
        this.$message.error('请先填写QQ邮箱');
        return;
      }
      
      // 检查邮箱格式
      if (!this.validateEmail(this.registerForm.email)) {
        this.$message.error('请输入正确的QQ邮箱格式');
        return;
      }
      
      this.codeSending = true;
      
      // 调用发送验证码接口
      sendVerificationCode({
        email: this.registerForm.email
      }).then(response => {
        this.$message.success('验证码已发送，请查收邮件');
        this.startCooldown(); // 开始倒计时
      }).catch(error => {
        console.error('发送验证码失败:', error);
        // 错误消息已由全局拦截器处理
      }).finally(() => {
        this.codeSending = false;
      });
    }
  }
}
</script>

<style lang="scss" scoped>
$bg: #283443;
$light_gray: #eee;
$blue: #409EFF;

.register-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  
  .register-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 120px 35px 0;
    margin: 0 auto;
    overflow: hidden;
    
    .el-form-item {
      margin-bottom: 20px;
      
      &:last-child {
        margin-bottom: 30px;
      }
    }
    
    .el-input {
      height: 48px;
      
      input {
        height: 48px;
        background: transparent;
        border: 1px solid rgba(255, 255, 255, 0.1);
        color: $light_gray;
        
        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: $light_gray !important;
        }
      }
    }
  }
  
  .verification-code {
    display: flex;
    
    .code-input {
      flex: 1;
    }
    
    .code-button {
      margin-left: 10px;
      width: 120px;
      height: 40px;
      margin-bottom: 10px;
    }
  }
  
  .form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
    padding-left: 5px;
  }
  
  .title-container {
    position: relative;
    margin-bottom: 40px;
    text-align: center;
    
    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0 auto 10px;
      font-weight: bold;
    }
    
    .subtitle {
      font-size: 16px;
      color: #909399;
      margin: 0;
    }
  }
  
  .register-button {
    width: 100%;
    height: 48px;
    margin-bottom: 30px;
    font-size: 16px;
  }
  
  .login-link {
    text-align: center;
    font-size: 14px;
    color: $light_gray;
    margin-bottom: 20px;
    
    span {
      color: $blue;
      cursor: pointer;
      
      &:hover {
        text-decoration: underline;
      }
    }
  }
}
</style> 